<?php

namespace Api\Cola;

use App\Cola\Model\ColaBill;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;

/**
 * 统计模块
 * */
#[Controller]
class StatController extends ColaBaseController
{

    /**
     * 获取时间支出总额和笔数
     * */
    #[PostMapping('getAnnualExpense')]
    public function getAnnualExpense()
    {
        $date = $this->request->input('date',);
        $cash_flow = $this->request->input('cash_flow');
        $userId = colaUser()->getId(); // 暂时写死

        $totalExpense = ColaBill::query()
            ->where('user_id', $userId)
            ->where('pay_time', $date)
            ->where('cash_flow', $cash_flow)
            ->sum('money');

        $totalTransactions = ColaBill::query()
            ->where('user_id', $userId)
            ->whereYear('pay_time', $date)
            ->where('cash_flow', $cash_flow)
            ->count();

        $result = [
            'total_expense' => $totalExpense,
            'total_transactions' => $totalTransactions
        ];
        return $this->response->success('success', $result);
    }

    /**
     *
     * */
    public function getCategoryExpense()
    {
        $year = $this->request->input('year', date('Y'));
        $userId = colaUser()->getId();

        $expenses = ColaBill::query()
            ->selectRaw('trade_cate_id, COUNT(*) as transactions, SUM(money) as amount')
            ->where('user_id', $userId)
            ->whereYear('pay_time', $year)
            ->where('cash_flow', 2)
            ->groupBy('trade_cate_id')
            ->with('tradeCategory')
            ->get();

        $totalExpense = $expenses->sum('amount');

        $result = $expenses->map(function ($expense) use ($totalExpense) {
            return [
                'category' => $expense->tradeCategory->name,
                'percentage' => round(($expense->amount / $totalExpense) * 100, 1),
                'transactions' => $expense->transactions,
                'amount' => $expense->amount
            ];
        });

        return $this->response->json($result);
    }


    /**
     * 获取支出和收入排行
     * */
    public function getExpenseRanking(RequestInterface $request): ResponseInterface
    {
        $year = $request->input('year', date('Y'));
        $userId = colaUser()->getId();

        $expenses = ColaBill::query()
            ->where('user_id', $userId)
            ->whereYear('pay_time', $year)
            ->where('cash_flow', 2)
            ->orderBy('money', 'desc')
            ->limit(10) // 假设只显示前10名
            ->get();

        $result = $expenses->map(function ($expense, $index) {
            return [
                'rank' => $index + 1,
                'description' => $expense->goods,
                'date' => $expense->pay_time,
                'amount' => $expense->money
            ];
        });

        return $this->response->json($result);
    }


}